﻿using KAs.Application;
using KAs.Application.Contract.Dto;
using KAs.Application.Contract.Svc;
using KAs.Common.Exceptions;
using KAs.SqlSugar;
using KAs.Utils.Oss;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions;
using RN.Note.Application.Contract.Dto;
using RN.Note.Application.Contract.Svc;
using RN.Note.Domain;
using SqlSugar;
using System.Diagnostics;

namespace RN.Note.Application;

public class NoteAppService : CommonCurdAppService<long, ReadingNote, ReadingNoteCreateDto, ReadingNoteCreateDto, ReadingNoteDto>, INoteAppService
{
    private ICurrentUserInfo _userInfo;
    private IAliyunOssService _aliyunOssService;

    public NoteAppService(IRepository<ReadingNote, long> repository,
        ICurrentUserInfo userInfo,
        IAliyunOssService aliyunOssService) : base(repository)
    {
        _userInfo = userInfo;
        _aliyunOssService = aliyunOssService;
    }

    public override async Task<bool> UpdateAsync(ReadingNoteCreateDto dto)
    {
        if (!dto.CoverImage.IsNullOrEmpty())
        {
            var hisEntity = await _repository.GetFirstAsync(x => x.Id == dto.Id);
            // 删除重复
            if (!hisEntity.CoverImage.IsNullOrEmpty())
                _aliyunOssService.DeleteFile(hisEntity.CoverImage);
        }
        return await base.UpdateAsync(dto);
    }

    public string UploadCoverImage(IFormFile file)
    {
        if (file == null) throw new BusinessException("上传文件为空");
        using var fs = file.OpenReadStream();
        var key = $"{Guid.NewGuid():N}{Path.GetExtension(file.FileName)}";
        _aliyunOssService.UploadFile(fs, key);
        return key;
    }

    public override async Task<PageReturnDto<ReadingNoteDto>> GetPageListAsync(PageReqDto pageReqDto)
    {
        Expressionable<ReadingNote> exp = Expressionable.Create<ReadingNote>();
        exp = exp.And(x => x.CreateUid == _userInfo.GetUserInfo().Uid);
        pageReqDto.OrderBy.OrderDicAppend<ReadingNote>(x => x.ReadedDate, OrderByType.Desc);
        var rtnVal = await PageAsync(pageReqDto.PageIndex, pageReqDto.PageSize, exp, pageReqDto.OrderBy);
        rtnVal.Data?.ForEach(item =>
        {
            if (!item.CoverImage.IsNullOrEmpty())
                item.CoverImage = _aliyunOssService.GenerateUrl(item.CoverImage);
        });
        return rtnVal;
    }

}